<template>
  <div class="User-panel">
    <div class="User-img">
      <img src="@/assets/img/other/icon-用户-hover.png" />
    </div>
    <div class="User-name">
      <span>{{ username }}</span>
    </div>
    <edit-outlined class="edit" @click="whiteboard()" />
    <div class="user-option">
      <div @click="OpenOption" class="OpenPanel">
        <img src="@/assets/img/other/icon-meum--normal.png" class="OpenPanelImg" />
        <div class="OptionMeum" v-if="OptionMeumBoolean === true">
          <div @click="SwitchAccountNumber">
            <span>切换账号</span>
          </div>
        </div>
      </div>
      <!-- 设置 -->
      <div class="whiteboard">
        <img src="@/assets/img/other/icon-set--normal.png" />
      </div>
      <!-- 退出 -->
      <div @click="ComponDialogComponent.Dialogboolean = true">
        <img src="@/assets/img/other/icon-exit--normal.png" />
      </div>
    </div>
  </div>
  <!-- 退出对话框 -->
  <DialogComponents :DialogComponent="ComponDialogComponent" @click="ComponDialogComponentFn"></DialogComponents>
  <treeModelThree ref="treeModelThree" hidden></treeModelThree>
  <root-board v-if="whiteboardTypes === true" />
</template>

<script>
import { defineComponent, ref, reactive, onMounted, isReactive } from "vue";
import router from "@/router";
import DialogComponents from "@/components/compon/DialogComponents.vue";
import treeModelThree from "@/components/newIndex/models/treeModelThree.vue";
import RootBoard from "@/views/elecboard/RootBoard.vue";
import { EditOutlined } from "@ant-design/icons-vue";
import { Golbal } from "@/assets/js/pubilcs";
import { postData, ThirdPartyDataSubmit } from "@/assets/js/pubilcs.js";
export default defineComponent({
  name: "UserOption",
  components: {
    DialogComponents,
    RootBoard,
    EditOutlined,
    treeModelThree,
  },
  setup() {
    let username = ref(sessionStorage.getItem("UserName"));
    let whiteboardTypes = ref(false);
    let OptionMeumBoolean = ref("false");
    //退出程序提示(通用对话框)
    let ComponDialogComponent = reactive({
      Dialogboolean: false,
      Msg: "是否退出程序?",
      Speanstyles: {},
      Buttonstyle: {
        background: "linear-gradient(-90deg, #0974D8, #3D8EF1, #7C7FF8)",
      },
      Buttonname: "确定",
    });

    async function ComponDialogComponentFn(fn) {
      if (fn === "Cancel") {
        ComponDialogComponent.Dialogboolean = false;
      }
      if (fn === "Ready") {
        ComponDialogComponent.Dialogboolean = false;
        const timeEnd = new Date().valueOf();
        console.log("退出时的时间戳：", timeEnd);
        let timeBegin = parseInt(sessionStorage.getItem("timeStart"));
        console.log("登录时的时间戳：", timeBegin);
        let differenceValue = timeEnd - timeBegin;
        console.log("时间戳的差：", differenceValue);
        const hour_ms = 60 * 60 * 1000; //一小时等于的毫秒数
        const min_ms = 60 * 1000; // 一分钟等于的毫秒数
        const ss_ms = 1000; //一秒等于的毫秒数
        const h_ms = parseInt(differenceValue / hour_ms); //获取小时部分
        const m_ms = parseInt((differenceValue % hour_ms) / min_ms); //获取分钟部分
        const s_ms = parseInt((differenceValue % min_ms) / 1000); //获取秒数
        console.log("时间戳的差转换成秒： ", s_ms);

        // 时间戳转换为日期
        let dateChange = new Date(timeBegin);
        let Y = dateChange.getFullYear() + "-";
        let M =
          (dateChange.getMonth() + 1 < 10
            ? "0" + (dateChange.getMonth() + 1)
            : dateChange.getMonth() + 1) + "-";
        let D =
          (dateChange.getDate() < 10
            ? "0" + dateChange.getDate()
            : dateChange.getDate()) + " ";
        let h =
          (dateChange.getHours() < 10
            ? "0" + dateChange.getHours()
            : dateChange.getHours()) + ":";
        let m =
          (dateChange.getMinutes() < 10
            ? "0" + dateChange.getMinutes()
            : dateChange.getMinutes()) + ":";
        let s =
          dateChange.getSeconds() < 10
            ? "0" + dateChange.getSeconds()
            : dateChange.getSeconds();
        let strDate = Y + M + D + h + m + s;
        console.log("开始时间:", strDate);

        let enablement = await Application.PostMessageAsync(Opcode.ThirdPartyArgsRequest);
        let enablementData = JSON.parse(enablement.ThirdPartyArgs);
        console.log('获取的学生数据', enablementData);
        if (enablementData) {
          // 如果运行任务再退出走if，不运行任务直接退出走else
          if (sessionStorage.getItem('ResultId')) {
            console.log('运行了');
            // 通过开始任务时获取的id调用接口获取分数
            postData("/api/TrainingResult/GetById", JSON.stringify({ Id: sessionStorage.getItem('ResultId') }), sessionStorage.getItem("token")).
              then(function (res) {
                console.log('=============================', res.result.result.score);
                ThirdPartyDataSubmit(
                  enablementData.url, sti({
                    s_course_id: parseInt(enablementData.course.s_course_id),
                    score: res.result.result.score,
                    t_students_id: parseInt(enablementData.student.t_students_id),
                    t_user_id: parseInt(enablementData.t_user_id),
                    u_user_id: parseInt(enablementData.u_user_id),
                    t_class_id: parseInt(enablementData.t_class_id),
                    start_time: strDate,
                    duration: parseInt(s_ms),
                  }
                  )
                ).then((res) => {
                  console.log('返回走的成功11111', res);
                  window.shutdown();
                })
              })
          } else {
            console.log('没运行');
            // 获取学生数据
            let enablement = await Application.PostMessageAsync(Opcode.ThirdPartyArgsRequest);
            let enablementData = JSON.parse(enablement.ThirdPartyArgs);
            console.log('获取的学生数据', enablementData);
            ThirdPartyDataSubmit(
              enablementData.url, sti({
                s_course_id: parseInt(enablementData.course.s_course_id),
                score: 0,
                t_students_id: parseInt(enablementData.student.t_students_id),
                t_user_id: parseInt(enablementData.t_user_id),
                u_user_id: parseInt(enablementData.u_user_id),
                t_class_id: parseInt(enablementData.t_class_id),
                start_time: strDate,
                duration: parseInt(s_ms),
              }
              )
            )
              .then((res) => {
                console.log('返回走的成功11111', res);
                window.shutdown();
              })
          }
        } else {
          window.shutdown();
        }

      }
    }
    // ===========================================================================================================================
    function sti(data) {
      // console.log('数据！！！！！！！', data);
      // 将{username:111,password:111} 转成 username=111&password=111
      let ret = '';
      for (let it in data) {
        // 如果要发送中文 编码
        ret += encodeURIComponent(it) + '=' + data[it] + '&'
      }
      return ret.substring(0, ret.length - 1)
    }


    //切换账号显示
    function OpenOption() {
      OptionMeumBoolean.value = true;
    }
    //切换账号功能
    function SwitchAccountNumber() {
      //控制防止再次自动登录
      Golbal.ExitLoadingBooelan = true;
      //设置临时缓存为空,防止下次登录还是上一次的产品信息
      sessionStorage.setItem("ProductActivationListArr", "");
      sessionStorage.setItem("ProductInventoryArr", "");
      // 清除组卷时选中的数据和状态
      // sessionStorage.setItem("AgreementList", "")
      sessionStorage.removeItem('AgreementList')
      router.push({
        name: "Loading",
      });
    }
    //切换账号点击任何地方隐藏
    function ProducOptionEventListener() {
      document.addEventListener("click", (e) => {
        let thisClassName = e.target.className;
        if (thisClassName !== "OpenPanelImg") {
          if (OptionMeumBoolean.value === true) {
            OptionMeumBoolean.value = false;
          }
        }
      });
    }
    //电子白板
    function whiteboard() {
      whiteboardTypes.value = !whiteboardTypes.value;
    }
    onMounted(async () => {
      //监听产品设置
      ProducOptionEventListener();
    });
    return {
      username,
      OpenOption,
      OptionMeumBoolean,
      SwitchAccountNumber,
      ComponDialogComponent,
      ComponDialogComponentFn,
      ProducOptionEventListener,
      whiteboardTypes,
      whiteboard,
      EditOutlined,
    };
  },
});
</script>
<style lang="less">
.User-panel {
  position: absolute;
  left: 120px;
  width: 1800px;
  height: 60px;
  background: #ffffff;
  z-index: 998;
}

.User-img {
  position: absolute;
  top: 0;
  // left: 0;
  width: 60px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  right: 462px;
}

.User-img img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}

.User-name {
  // width: 160px;
  // height: 100%;
  // display: flex;
  // justify-content: flex-start;
  // align-items: center;
  // margin-left: 10px;
  // padding-left: 40px;
  font-size: 18px;
  font-family: Source Han Sans CN;
  font-weight: 500;
  color: #1b1b1d;
  line-height: 56px;
  position: absolute;
  right: 425px;
  top: 3px;
}

.user-option {
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.user-option>div img {
  width: auto;
  height: auto;
  max-height: 100%;
  max-width: 100%;
  cursor: pointer;
}

.OptionMeum {
  position: absolute;
  width: 120px;
  height: 50px;
  top: 50px;
  left: -8px;
  background: #ffffff;
  border-radius: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.OptionMeum>div {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80%;
  height: 80%;
  border-radius: 15px;
  color: #ffffff;
  font-size: 14px;
  background: linear-gradient(0deg, #0974d8, #3d8ef1, #7c7ff8);
  cursor: pointer;
}

.edit {
  color: rgba(129, 133, 156) !important;
  font-size: 24px;
  position: absolute;
  top: 17px;
  right: 340px;
}
</style>
